package com.dp.mallchat.transaction.aspect;

import cn.hutool.core.date.DateUtil;
import com.dp.mallchat.common.utils.JsonUtils;
import com.dp.mallchat.transaction.annotation.SecureInvoke;
import com.dp.mallchat.transaction.domain.dto.SecureInvokeDTO;
import com.dp.mallchat.transaction.domain.entity.SecureInvokeRecord;
import com.dp.mallchat.transaction.service.SecureInvokeHolder;
import com.dp.mallchat.transaction.service.SecureInvokeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: dupeng
 * @CreateTime: 2024-07-01  10:44
 * @Description: SecureInvoke切面
 */
@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 1)//确保最先执行
public class SecureInvokeAspect {

    @Autowired
    private SecureInvokeRecordService secureInvokeService;


    @Around(value = "@annotation(secureInvoke)")
    public Object around(ProceedingJoinPoint joinPoint, SecureInvoke secureInvoke) throws Throwable {
        //是否开启事务
        boolean actualTransactionActive = TransactionSynchronizationManager.isActualTransactionActive();
        // 未开启事务，直接返回
        if (SecureInvokeHolder.isInvokeHolder() || !actualTransactionActive){
            return joinPoint.proceed();
        }

        //获取方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取方法类型
        List<String> parameters = Stream.of(method.getParameterTypes()).map(Class::getName).collect(Collectors.toList());

        //构建方法请求：方法全限定名+方法名+方法入参+方法入参类型
        SecureInvokeDTO dto = SecureInvokeDTO.builder()
                .args(JsonUtils.toStr(joinPoint.getArgs()))
                .className(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(JsonUtils.toStr(parameters))
                .build();
        SecureInvokeRecord record = SecureInvokeRecord.builder()
                .secureInvokeDTO(dto)
                .maxRetryTimes(secureInvoke.maxRetryTimes())
                .nextRetryTime(DateUtil.offsetMinute(new Date(), (int) SecureInvokeRecordService.RETRY_INTERVAL_MINUTES))   //日期偏移
                .build();

        //执行
        secureInvokeService.invoke(record,secureInvoke.isAsync());
        return null;
    }



}
